// pages/Wrong/Wrong.js
const WRONG_KEY = 'wrongQuestions';
const API_BASE  = 'https://tihaidengta.xyz';

Page({
  data: {
    isDarkMode: false,
    showThemePanel: false,

    questions: [],        // 从缓存中拉取
    currentIndex: 0,
    userAnswer: '',
    answeredQuestions: [],
    showResult: false,
    correctCount: 0,

    // 触摸滑动相关
    slideTransform: '',
    startTouchX: 0
  },

  onLoad() {
    this.setData({
      isDarkMode: wx.getStorageSync('isDarkMode') || false
    });
    this.loadWrongQuestions();
  },

  onShow() {
    this.loadWrongQuestions();
  },

  // 从本地取出错题
  loadWrongQuestions() {
    const raw = wx.getStorageSync(WRONG_KEY) || [];
    // 格式化每道题的数据结构，与 chapterPractice 兼容
    const questions = raw.map(item => ({
      ...item,
      optionsArray: item.optionsArray || [], // 题目里已带选项
      userAnswer: ''
    }));
    this.setData({
      questions,
      currentIndex: 0,
      answeredQuestions: [],
      showResult: false,
      correctCount: 0
    });
  },

  // 滑动切题
  touchStart(e) {
    this.setData({ startTouchX: e.changedTouches[0].pageX });
  },
  touchMove(e) {
    const move = e.changedTouches[0].pageX - this.data.startTouchX;
    this.setData({ slideTransform: `translateX(${Math.min(Math.max(move, -100),100)}px)` });
  },
  touchEnd(e) {
    const endX = e.changedTouches[0].pageX;
    const { startTouchX } = this.data;
    if (endX - startTouchX > 50) this.prevQuestion();
    else if (startTouchX - endX > 50) this.nextQuestion();
    this.setData({ slideTransform: '' });
  },

  // 单选题答题
  onSelect(e) {
    const uniq = e.currentTarget.dataset.uniqid;
    const key  = e.currentTarget.dataset.key;
    const idx  = this.data.questions.findIndex(q => q.uniqId === uniq);
    if (idx < 0) return;

    const q = this.data.questions[idx];
    if (q.userAnswer) return; // 已答过

    q.userAnswer = key;
    // 在错题练习里，答错依然保留，答对可视需要不再重入错题库
    const correct = key === q.answer;
    if (correct) this.setData({ correctCount: this.data.correctCount + 1 });

    // 给每个选项打上状态类
    q.optionsArray = q.optionsArray.map(opt => ({
      ...opt,
      statusClass: opt.key === q.answer 
        ? 'correct' 
        : (opt.key === key ? 'wrong' : '')
    }));

    this.updateAfterAnswer(idx, q, correct);
  },

  // 文本题输入、提交同章练逻辑
  onInputAnswer(e) {
    this.setData({ userAnswer: e.detail.value });
  },
  submitTextAnswer() {
    const idx = this.data.currentIndex;
    const q   = this.data.questions[idx];
    if (q.userAnswer) return;

    const val = (this.data.userAnswer || '').trim();
    q.userAnswer = val;
    const correct = val === (q.answer || '').trim();
    if (correct) this.setData({ correctCount: this.data.correctCount + 1 });
    this.updateAfterAnswer(idx, q, correct);
  },

  // 所有题型答后通用处理
  updateAfterAnswer(idx, question, correct) {
    const qs = this.data.questions;
    qs[idx] = question;

    this.setData({
      questions: qs,
      answeredQuestions: [...new Set([...this.data.answeredQuestions, idx])],
      showResult: true
    });

    if (correct) {
      setTimeout(() => this.nextQuestion(), 800);
    }
  },

  // 切题
  changeQuestion(e) {
    const ni = e.detail.index;
    this.setData({
      currentIndex: ni,
      userAnswer: '',
      showResult: false,
      slideTransform: ''
    });
  },
  prevQuestion() {
    if (this.data.currentIndex > 0) {
      const ni = this.data.currentIndex - 1;
      this.setData({
        currentIndex: ni,
        userAnswer: this.data.questions[ni].userAnswer,
        showResult: false
      });
    }
  },
  nextQuestion() {
    const ni = this.data.currentIndex + 1;
    if (ni < this.data.questions.length) {
      this.setData({
        currentIndex: ni,
        userAnswer: this.data.questions[ni].userAnswer,
        showResult: false
      });
    } else {
      wx.showModal({
        title: '练习完成',
        content: `共 ${this.data.questions.length} 题，答对 ${this.data.correctCount} 题`,
        showCancel: false
      });
    }
  },

  // 深色模式开关
  toggleThemePanel() {
    this.setData({ showThemePanel: !this.data.showThemePanel });
  },
  toggleDarkMode(e) {
    const dark = e.detail.value;
    wx.setStorageSync('isDarkMode', dark);
    this.setData({ isDarkMode: dark });
  },

  // 底部控制条保持一致
  finishPractice() {
    wx.showModal({
      title: '练习完成',
      content: `共 ${this.data.questions.length} 题，答对 ${this.data.correctCount} 题`,
      showCancel: false
    });
  }
});
